package com.jsnider.pokedex;

import java.util.ArrayList;
import java.util.List;
 
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
 
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
 
public class EditPokemon extends Activity {
 
    EditText p_name;
    EditText p_type;
    EditText p_number;
    EditText p_info;
    Button btnSave;
    Button btnDelete;
 
    String p_id;
    int success;
    JSONObject pokemon;
 
    // Progress Dialog
    private ProgressDialog pDialog;
 
    // JSON parser class
    JSONParser jsonParser = new JSONParser();
 
    // single pokemon url
    private static final String url_pokemon_details = "http://compsci.lewiscenter.org/~jsnider/1styear/get_pokemon_details.php";
 
    // url to update product
    private static final String url_update_pokemon = "http://compsci.lewiscenter.org/~jsnider/1styear/pokemon_update.php";
 
    // url to delete product
    private static final String url_delete_pokemon = "http://compsci.lewiscenter.org/~jsnider/1styear/pokemon_delete.php";
 
    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_POKEMON = "pokemon";
    private static final String TAG_P_ID = "p_id";
    private static final String TAG_P_NAME = "p_name";
    private static final String TAG_P_TYPE = "p_type";
    private static final String TAG_P_NUMBER = "p_number";
    private static final String TAG_P_INFO = "p_info";
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_pokemon);
 
        // save button
        btnSave = (Button) findViewById(R.id.btnSave);
        btnDelete = (Button) findViewById(R.id.btnDelete);
 
        // getting product details from intent
        Intent i = getIntent();
 
        // getting product id (pid) from intent
        p_id = i.getStringExtra(TAG_P_ID);
 
        // Getting complete pokemon details in background thread
        new GetPokemonDetails().execute();
 
        // save button click event
        btnSave.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View arg0) {
                // starting background task to update product
                new SavePokemonDetails().execute();
            }
        });
 
        // Delete button click event
        btnDelete.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View arg0) {
                // deleting pokemon in background thread
                new DeletePokemon().execute();
            }
        });
 
    }
 
    /**
     * Background Async Task to Get complete product details
     * */
    class GetPokemonDetails extends AsyncTask<String, String, String> {
 
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(EditPokemon.this);
            pDialog.setMessage("Loading pokemon details. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
 
        /**
         * Getting product details in background thread
         * */
        protected String doInBackground(String... args) {
 
            // updating UI from Background Thread
         //   runOnUiThread(new Runnable() {
         //       public void run() {
                    // Check for success tag
                    try {
                        // Building Parameters
                        List<NameValuePair> params = new ArrayList<NameValuePair>();
                        params.add(new BasicNameValuePair("p_id", p_id));
 
                        // getting pokemon details by making HTTP request
                        // Note that product details url will use GET request
                        JSONObject json = jsonParser.makeHttpRequest(
                                url_pokemon_details, "GET", params);
 
                        // check your log for json response
                        Log.d("Single Pokemon Details", json.toString());
 
                        // json success tag
                        success = json.getInt(TAG_SUCCESS);
                        if (success == 1) {
                            // successfully received product details
                            JSONArray productObj = json
                                    .getJSONArray(TAG_POKEMON); // JSON Array
 
                            // get first product object from JSON Array
                             pokemon = productObj.getJSONObject(0);


 
                        }else{
                            // POKEMON with pid not found
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
           //     }
           // });
 
            return null;
        }
 
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once got all details
            pDialog.dismiss();
            
         runOnUiThread(new Runnable() {
          public void run() {
            
            if (success == 1) {
                // successfully received product details

                // product with this pid found
                // Edit Text
                p_name = (EditText) findViewById(R.id.p_name);
                p_number = (EditText) findViewById(R.id.p_number);
                p_info = (EditText) findViewById(R.id.p_info);
                p_type = (EditText) findViewById(R.id.p_type);

                // display product data in EditText
                try {
					p_name.setText(pokemon.getString(TAG_P_NAME));
                p_type.setText(pokemon.getString(TAG_P_TYPE));
                p_info.setText(pokemon.getString(TAG_P_INFO));
                p_number.setText(pokemon.getString(TAG_P_NUMBER));
			} catch (JSONException e) {
				e.printStackTrace();
			}
              }
             }
           });            
            
            
            
            
            
        }
    }
 
    /**
     * Background Async Task to  Save product Details
     * */
    class SavePokemonDetails extends AsyncTask<String, String, String> {
 
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(EditPokemon.this);
            pDialog.setMessage("Saving product ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
 
        /**
         * Saving product
         * */
        protected String doInBackground(String... args) {
 
            // getting updated data from EditTexts
            String name = p_name.getText().toString();
            String type = p_type.getText().toString();
            String info = p_info.getText().toString();
            String number = p_number.getText().toString();
 
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair(TAG_P_ID, p_id));
            params.add(new BasicNameValuePair(TAG_P_NAME, name));
            params.add(new BasicNameValuePair(TAG_P_TYPE, type));
            params.add(new BasicNameValuePair(TAG_P_NUMBER, number));
            params.add(new BasicNameValuePair(TAG_P_INFO, info));
 
            // sending modified data through http request
            // Notice that update product url accepts POST method
            //should be success message back
            JSONObject json_update = jsonParser.makeHttpRequest(url_update_pokemon,
                    "POST", params);
 
            // check json success tag
            try {
                int success = json_update.getInt(TAG_SUCCESS);
 
                if (success == 1) {
                    // successfully updated
                    Intent i = getIntent();
                    // send result code 100 to notify about product update
                    setResult(100, i);
                    pDialog.dismiss();
                } else {
                    // failed to update product
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
 
            return null;
        }
 
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once product uupdated
            //pDialog.dismiss();
            finish();
        }
    }
 
    /*****************************************************************
     * Background Async Task to Delete Product
     * */
    class DeletePokemon extends AsyncTask<String, String, String> {
 
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(EditPokemon.this);
            pDialog.setMessage("Deleting Product...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
 
        /**
         * Deleting product
         * */
        protected String doInBackground(String... args) {
 
            // Check for success tag
            int success;
            try {
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("p_id", p_id));
 
                // getting product details by making HTTP request
                JSONObject json = jsonParser.makeHttpRequest(
                        url_delete_pokemon, "POST", params);
 
                // check your log for json response
                Log.d("Delete Product", json.toString());
 
                // json success tag
                success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    // product successfully deleted
                    // notify previous activity by sending code 100
                    Intent i = getIntent();
                    // send result code 100 to notify about product deletion
                    setResult(100, i);
                    finish();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
 
            return null;
        }
 
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once product deleted
            pDialog.dismiss();
 
        }
 
    }
}